const  Koa = require('koa'); // http ,包装过的http
const Router = require('koa-router');

const app = new Koa();
const router = new Router();


// ①路由
router.get('/', (ctx, next) => {
    ctx.body = '首页';
});

router.get('/user', (ctx, next)=>{
    ctx.body = 'user';
})


// ②添加子路由
const listRouter = new Router();

listRouter.get('/', (ctx, next)=>{
    ctx.body = '列表页';
})

listRouter.get('/detail', (ctx, next)=>{
    ctx.body = '详情页面';
})


// ③添加前缀路由
const itemRouter = new Router({
    prefix: '/item'
});

itemRouter.get('/add', (ctx, next)=>{
    ctx.body = '添加item'
})

itemRouter.get('/delete', (ctx, next)=>{
    ctx.body = '删除item'
})

// ④动态路由
const goodsRouter = new Router();
goodsRouter.get('/goods/:id', (ctx, next)=>{

    ctx.body = '商品编号:' + ctx.params.id
})


// ⑤ 路由重定向
router.redirect('/admins', '/user', 301)

// ⑥ url生成器 需要路由存在才能生成
// 相当于生成 /goods/3/?limit=1
router.get('good', '/goods/:id', (ctx, next) => {});
console.log(router.url('good', 3))
console.log(router.url('good', {id: 3}))
console.log(router.url('good', {id: 3}, { query: { limit: 1 } }))


// 挂载路由
router.use('/list', listRouter.routes()) // 挂载子路由
router.use(itemRouter.routes()) // 挂载带前缀的路由
router.use(goodsRouter.routes()) // 挂载动态路由
app.use(router.routes());
app.use(router.allowedMethods());
//------- router end -------


app.listen('3000');